package com.swjd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.swjd.mapper.StudentMapper;
import com.swjd.pojo.Student;
import com.swjd.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 刘涛
 * @create 2021/11/9 11:09
 */
@ResponseBody
@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private StudentService studentService;

    @RequestMapping("/findById")
    public Student findById(Integer id) throws Exception {
        if (id == null) {
            throw new Exception("id为空");
        }
        return studentMapper.selectById(id);
    }

    @RequestMapping("/getById")
    public Student getById(Integer id) throws Exception {
        if (id == null) {
            throw new Exception("id为空");
        }
        return studentService.getById(id);
    }

    @RequestMapping("/insert")
    public String insert() {
        ArrayList<Student> students = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Student student = new Student();
            student.setAge(18 + i);
            student.setEmail("123@qq.com");
            student.setName("李四");
            student.setStatus(1);
            students.add(student);
        }
        boolean save = studentService.saveBatch(students);
        if (save) {
            return "成功";
        }
        return "失败";
    }

    @RequestMapping("/getByName")
    public List<Student> getByName(String name) throws Exception {
        if (name == null) {
            throw new Exception("id为空");
        }
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.eq("name", name);
        return studentService.list(qw);
    }

    @RequestMapping("/findAll")
    public List<Student> findAll() {
        return studentMapper.selectList(null);
    }
}
